package com.example.idgrenternate.controller;

import com.example.idgrenternate.util.IdGrenateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Controller
@RequestMapping
public class shortUrlController {

    private HttpServletResponse response;
    private  final  static String SHORT_URL_KEY="short:url";

    @Autowired
    private RedisTemplate  redisTemplate;


    /**
     * 长链接转换为短链接
     * 实现原理：长链接转换未短加密传key，然后存储在redis的hash结构钟
     */

    @GetMapping(value="/encode")
    public String encode(@RequestParam  String url){

        //一个长连接转换为4个短加密传key
        String [] keys= IdGrenateUtils.shortUrl(url);
        String key=keys[0];
        //用hash存储，key=加密串，value=原始url
        this.redisTemplate.opsForHash().put(SHORT_URL_KEY,key,url);

        return "http://127.0.0.1:9090/"+key;
    }

    /**
     * 冲顶小到原始的url
     * 实现原理：通过短加密串KEY到redis找出原始URL，然后重定向出去
     */
    @GetMapping(value="/{key}")
    public void decode(@PathVariable String key) {
        //到redis中把原始url找出来
        String url=(String)this.redisTemplate.opsForHash().get(SHORT_URL_KEY,key);
        try {
            response.sendRedirect(url);
        }catch (Exception e){
            e.getMessage();
        }
    }
}
